package com.iw.core.security.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.iw.core.orm.hibernate.BaseDao;
import com.iw.core.orm.hibernate.BaseService;
import com.iw.core.security.dao.UsersDao;
import com.iw.core.security.entity.Resources;
import com.iw.core.security.entity.Roles;
import com.iw.core.security.entity.Users;

@Service
@Transactional
public class ResourcesService extends BaseService<Resources> {

    @Resource
    private UsersDao usersDao;

    @Override
    @Resource(name = "resourcesDao")
    public void setBaseDao(BaseDao<Resources> baseDao) {
        this.baseDao = baseDao;
    }

    public List<Resources> findMenu() {
        return baseDao.findList("from Resources where isMenu = 1 order by gorder");
    }

    public List<Resources> findMenu(Integer userId) {
        List<Resources> list = new ArrayList<Resources>();
        Users user = usersDao.find(userId);
        Set<Roles> roles = user.getRoles();
        for (Roles role : roles) {
            //角色被禁用了，将无权限
            if (role.isEnable()) {
                list.addAll(role.getResources());
            }
        }
        List<Resources> listNotRepeat = new ArrayList<Resources>();
        for (Resources r : list) {
            if (!listNotRepeat.contains(r)) {
                listNotRepeat.add(r);
            }
        }
        Collections.sort(listNotRepeat, new SortByGorder());
        return listNotRepeat;
    }

    // 按gorder排序
    class SortByGorder implements Comparator<Resources> {
        @Override
        public int compare(Resources o1, Resources o2) {
            if (o1.getGroup().getGorder() < o2.getGroup().getGorder()) {
                return -1;
            } else if (o1.getGroup().getGorder() > o2.getGroup().getGorder()) {
                return 1;
            } else {
                if (o1.getGorder() < o2.getGorder()) {
                    return -1;
                } else {
                    return 1;
                }
            }
        }
    }
}
